#include "watchdog/WatchdogServerAgent.h"

#include "common/log/log.h"

#include <iostream>
using namespace std;

WatchdogServerAgent::WatchdogServerAgent(/* args */){}

WatchdogServerAgent::WatchdogServerAgent(const SocketAddress &addr):TCPAgent(addr){

}
WatchdogServerAgent::WatchdogServerAgent(const TCPSocket &sock, const SocketAddress &addr):TCPAgent(sock, addr){

}

WatchdogServerAgent::~WatchdogServerAgent(){}

int WatchdogServerAgent::init(){
    if (this->connect() != SUCCESSFUL){
        ERROR_LOG("in ServerAgent::init connect server error");
        return FAILED;
    }
    return SUCCESSFUL;
}

int WatchdogServerAgent::connectAfter( bool bConnect){
    if(bConnect){
        MsgHeader msg;
        msg.cmd = 1;
        msg.length = 10;
        msg.para1 = 111;
        char *buf = new char[10 + 1];
        memset(buf, 0, 10 + 1);
        memset(buf, 'd', 10);
        sendPackage(msg, buf);

        delete[] buf;
        buf = NULL;
        return SUCCESSFUL;
    }else{
        return FAILED;
    }
}

void WatchdogServerAgent::readBack( InReq &req ){
    cout << req.m_msgHeader.cmd << endl;
    cout << req.m_msgHeader.para1 << endl;
    cout << req.ioBuf << endl;
}
void WatchdogServerAgent::writeBack( bool result){

}

int WatchdogServerAgent::sendPackage( MsgHeader &header, const char *dataStr ){
    uint32_t msgLength = header.length + sizeof(MsgHeader);
    char *sendBuf = new char[msgLength + 1];
    memset(sendBuf, 0, msgLength + 1);
    memcpy(sendBuf, &header, sizeof(MsgHeader));
    if (dataStr != NULL){
        memcpy(sendBuf + sizeof(MsgHeader), dataStr, header.length);
    }

    if (this->writeToBuffer(sendBuf, msgLength) == FAILED){
        return FAILED;
    }

    return SUCCESSFUL;
}

void WatchdogServerAgent::recycler( void ){
    cout << "serverAgent deleted" << endl;
}